<template>
  <show-container title="">
    <Card dis-hover :bordered="false">
      <p slot="title">Role Authorization</p>
      <Form
        :style="{ width: '520px' }"
        :rules="formRules"
        :model="formItem"
        ref="formItem"
        :label-width="180"
      >
        <FormItem label="RoleName">
          <Input
            v-model="roleInfo.roleName"
            readonly
            placeholder="Role Name"
          ></Input>
        </FormItem>
        <FormItem label="Permissions">
          <Tree
            :data="treeData"
            :render="renderContent"
            ref="permissionsTree"
            empty-text="no data"
            show-checkbox
          ></Tree>
        </FormItem>
        <FormItem>
          <Button type="primary" :loading="loading" @click="handleAuthor"
            >Save Authorization</Button
          >
        </FormItem>
      </Form>
    </Card>
  </show-container>
</template>
<script>
import { authorRole } from "@/api/role.js";
import { list } from "@/api/permissions.js";
import { AddPageMixin } from "@/mixins/ListMixins.js";
export default {
  mixins: [AddPageMixin],
  data() {
    return {
      formItem: {
        menuIds: [],
        roleId: 0
      },
      roleInfo: {},
      treeData: [],
      formRules: {},
      loading: false
    };
  },
  async created() {
    this.roleInfo = await JSON.parse(this.$route.query.data);
    this.formItem.roleId = this.roleInfo.id;

    list().then(({ data }) => {
      this.treeData = data.children;
    });
  },
  methods: {
    handleAuthor() {
      let rs = this.$refs.permissionsTree.getCheckedNodes();
      let arr = [];
      rs.forEach(item => {
        arr.push(item.id);
        item.children.forEach(cItem => {
          arr.push(cItem.id);
        });
      });
      this.formItem.menuIds = arr;
      if (arr.length === 0) {
        this.$Message.error("Please select permission");

        return;
      }
      authorRole(this.formItem).then(() => {
        this.$Message.success("Authorization Success");
        this.triggerRefresh();
        this.$closePage();
      });
    },
    renderContent(h, { data }) {
      return h("span", data.label);
    }
  }
};
</script>
